package com.lp.biz.operations.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lp.biz.operations.mapper.BlackListMapper;
import com.lp.biz.operations.mapper.InvoiceMapper;
import com.lp.biz.operations.model.entity.Invoice;
import com.lp.biz.operations.model.query.BlackListQuery;
import com.lp.biz.operations.model.vo.InvoiceList;
import com.lp.biz.operations.service.OperationsService;
import com.lp.common.entity.PageParams;
import com.lp.common.exception.BaseException;
import com.lp.common.utils.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.lp.common.constant.CommonConstant.NEGATE;
import static com.lp.common.constant.CommonConstant.SURE;
import static com.lp.common.utils.Tools.copyPage;

/**
 * @program: backend
 * @description:
 * @author: Ke.Song
 * @since: 2024-06-30 23:47:23
 */
@Service
public class OperationsServiceImpl implements OperationsService {

    @Autowired
    private InvoiceMapper invoiceMapper;
    @Autowired
    private BlackListMapper blackListMapper;

    @Override
    public CommonResult getBlackList(BlackListQuery query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        return CommonResult.restPage(blackListMapper.getBlackList(query));
    }

    @Override
    public CommonResult invoiceList(PageParams query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        List<Invoice> invoices = invoiceMapper.selectList(new QueryWrapper<Invoice>().lambda().orderByDesc(Invoice::getCreateAt));
        Page<InvoiceList> invoiceLists = copyPage(new Page<>(), invoices);
        for (Invoice invoice : invoices) {
            invoiceLists.add(InvoiceList.builder(invoice));
        }
        return CommonResult.restPage(invoiceLists);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateInvoiceStatus(Integer invoiceId) {
        Invoice invoice = invoiceMapper.selectById(invoiceId);
        if (invoice == null) {
            throw new BaseException("发票输入错误");
        }
        invoice.setStatus(invoice.getStatus().equals(NEGATE) ? SURE : NEGATE);
        invoiceMapper.updateById(invoice);
    }
}
